package com.example.langchain4j.service;

import cn.hutool.json.JSONUtil;
import com.deepoove.poi.XWPFTemplate;
import com.example.langchain4j.common.constant.PromptConstant;
import com.example.langchain4j.common.exception.BusinessException;
import com.example.langchain4j.utils.DocumentUtils;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class DifyChangeService {
//    public void generationShenpibiao(MultipartFile file1, MultipartFile file2, HttpServletResponse response) {
//        OutputStream out = null;
//        BufferedOutputStream bos = null;
//        try {
//            // 提取文档内容
//            String document1Content = DocumentUtils.extractTextFromWord(file1);
//            String document2Content = DocumentUtils.extractTextFromWord(file2);
//
//            // 加载resource下面的json模板
//            String jsonTemplate = TemplateUtils.loadCaseApprovalTemplate("立案审批表示例.txt");
//
//            String jsonResult = assistant.chat(document1Content,document2Content,jsonTemplate);
//            Map<String, Object> resultMap = JSONUtil.toBean(jsonResult, Map.class);
//            System.out.println(resultMap);
//
//            // 从resources目录加载审批表.docx模板
//            ClassPathResource resource = new ClassPathResource("行政处罚立案审批表template.docx");
//            InputStream templateInputStream = resource.getInputStream();
//            XWPFTemplate template = XWPFTemplate.compile(templateInputStream).render(resultMap);
//
//
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-disposition","attachment;filename=\""+"out_template.docx"+"\"");
//            out = response.getOutputStream();
//            bos = new BufferedOutputStream(out);
//            template.write(bos);
//            bos.flush();
//            out.flush();
//        } catch (IOException e) {
//            throw new BusinessException(500, "生成文档失败！" + e.getMessage());
//        } finally {
//            try {
//                if (out != null) {
//                    out.close();
//                }
//                if (bos != null) {
//                    bos.close();
//                }
//            } catch (IOException e) {
//                log.error("关闭流异常！", e);
//            }
//        }
//    }

    @Resource
    @Qualifier("chatLanguageModel")
    private ChatLanguageModel chatLanguageModel;

    private static final String GENERATED_DIR = "src/main/resources/generated";

    public Map<String, Object> generationShenpibiao(MultipartFile file1, MultipartFile file2, HttpServletResponse response) {
        try {
            // 提取文档内容
            String document1Content = DocumentUtils.extractTextFromWord(file1);
            String document2Content = DocumentUtils.extractTextFromWord(file2);

            // 创建提示模板
            String generalJianYaoAnQing = PromptConstant.generalJianYaoAnQing;
            PromptTemplate promptTemplate1 = PromptTemplate.from(generalJianYaoAnQing);
            HashMap<String, Object> vary1 = new HashMap<>();
            vary1.put("document1Content", document1Content);
            vary1.put("document2Content", document2Content);
            Prompt prompt1 = promptTemplate1.apply(vary1);

            // 调用模型 获取简要案情
            ChatResponse chatResponse1 = chatLanguageModel.chat(prompt1.toUserMessage());
            String jianyaoanqingRes = chatResponse1.aiMessage().text();
            log.info("------------------------------------------------------------------------------------");
            log.info("生成的简要案情描述：{}", jianyaoanqingRes);

            // 结合简要案情描述 调用模型 生成审批表json
            String generalShenpibiaoJson = PromptConstant.generalShenpibiaoJson;
            vary1.put("jianyaoanqingRes", jianyaoanqingRes);
            PromptTemplate promptTemplate2 = PromptTemplate.from(generalShenpibiaoJson);
            Prompt prompt2 = promptTemplate2.apply(vary1);
            ChatResponse chatResponse2 = chatLanguageModel.chat(prompt2.toUserMessage());
            String shenpibiaoJsonRes = chatResponse2.aiMessage().text();

            // 清理JSON字符串，移除可能的markdown标记
            shenpibiaoJsonRes = cleanJsonString(shenpibiaoJsonRes);

            log.info("------------------------------------------------------------------------------------");
            log.info("生成的审批表json：{}", shenpibiaoJsonRes);

            log.info("------------------------------------------------------------------------------------");

            // 确保generated目录存在
            java.nio.file.Path generatedPath = java.nio.file.Paths.get(GENERATED_DIR);
            if (!java.nio.file.Files.exists(generatedPath)) {
                java.nio.file.Files.createDirectories(generatedPath);
            }

            // 生成文件名
            java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
            String timestamp = java.time.LocalDateTime.now().format(formatter);
            String fileName = "行政处罚立案审批表_" + timestamp + ".docx";
            String filePath = GENERATED_DIR + "/" + fileName;

            // 填充word模板并保存到文件
            Map<String, Object> resultMap = JSONUtil.toBean(shenpibiaoJsonRes, Map.class);
            ClassPathResource resource = new ClassPathResource("行政处罚立案审批表template.docx");
            InputStream templateInputStream = resource.getInputStream();
            XWPFTemplate template = XWPFTemplate.compile(templateInputStream).render(resultMap);

            // 保存到本地文件
            java.io.FileOutputStream fileOut = new java.io.FileOutputStream(filePath);
            template.write(fileOut);
            fileOut.close();
            template.close();

            log.info("审批表文件已保存: {}", filePath);

            // 准备返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("fileName", fileName);
            result.put("filePath", "http://localhost:8018/api/dify/generated/" + fileName);
            result.put("jsonData", shenpibiaoJsonRes);
            result.put("message", "审批表生成成功");

            log.info("审批表生成完成，返回结果: {}", result);
            return result;

        }catch (IOException e){
            log.error("解析文档失败", e);
            throw new BusinessException(500,"解析文档失败: " + e.getMessage());
        }catch (Exception e) {
            log.error("生成审批表失败", e);
            throw new BusinessException(500, "生成审批表失败: " + e.getMessage());
        }
    }

    /**
     * 清理JSON字符串，移除markdown代码块标记和额外说明
     * 特别处理推理模型（如qwq）的思考过程输出
     */
    private String cleanJsonString(String jsonString) {
        if (jsonString == null || jsonString.trim().isEmpty()) {
            return jsonString;
        }

        String cleaned = jsonString.trim();

        // 移除开头的markdown标记
        if (cleaned.startsWith("```json")) {
            cleaned = cleaned.substring(7);
        } else if (cleaned.startsWith("```")) {
            cleaned = cleaned.substring(3);
        }

        // 移除结尾的markdown标记
        if (cleaned.endsWith("```")) {
            cleaned = cleaned.substring(0, cleaned.length() - 3);
        }

        cleaned = cleaned.trim();

        // 特殊处理：如果内容包含思考过程（常见于推理模型），尝试提取JSON部分
        // 查找最后一个完整的JSON对象（从最后一个 } 往前找到对应的 {）
        int lastBrace = cleaned.lastIndexOf('}');
        if (lastBrace != -1) {
            // 从lastBrace往前找匹配的 {
            int braceCount = 1;
            int firstBrace = lastBrace - 1;
            while (firstBrace >= 0 && braceCount > 0) {
                if (cleaned.charAt(firstBrace) == '}') {
                    braceCount++;
                } else if (cleaned.charAt(firstBrace) == '{') {
                    braceCount--;
                }
                firstBrace--;
            }
            firstBrace++; // 调整到 { 的位置

            if (firstBrace >= 0 && braceCount == 0) {
                // 找到了完整的JSON对象
                String potentialJson = cleaned.substring(firstBrace, lastBrace + 1);
                // 验证是否像JSON（简单检查：包含引号和冒号）
                if (potentialJson.contains("\"") && potentialJson.contains(":")) {
                    cleaned = potentialJson;
                    log.info("从推理模型输出中提取到JSON，长度: {}", cleaned.length());
                }
            }
        }

        // 如果上面没有找到，使用原来的逻辑：查找第一个 { 和最后一个 }
        if (!cleaned.startsWith("{")) {
            int firstBrace = cleaned.indexOf('{');
            int lastBraceSimple = cleaned.lastIndexOf('}');

            if (firstBrace != -1 && lastBraceSimple != -1 && firstBrace < lastBraceSimple) {
                // 提取 {} 之间的内容
                cleaned = cleaned.substring(firstBrace, lastBraceSimple + 1);
            }
        }

        return cleaned.trim();
    }

    @Resource
    private InterrogationGenerationService interrogationGenerationService;

    /**
     * 生成笔录 - 使用立案审批表JSON数据
     * @param caseApprovalJson 立案审批表的JSON字符串
     * @param response HTTP响应对象
     * @return 包含生成结果的Map
     */
    public Map<String, Object> generationBilu(String caseApprovalJson, HttpServletResponse response) {
        try {
            log.info("开始生成笔录，使用立案审批表JSON数据");

            // 调用InterrogationGenerationService生成笔录
            Map<String, Object> result = interrogationGenerationService.generateInterrogationRecord(
                    caseApprovalJson, null);

            log.info("笔录生成成功");
            return result;

        } catch (Exception e) {
            log.error("生成笔录失败", e);
            throw new BusinessException(500, "生成笔录失败: " + e.getMessage());
        }
    }

    /**
     * 生成笔录 - 从立案审批表Word文件
     * @param file1 立案审批表Word文件
     * @param response HTTP响应对象
     * @return 包含生成结果的Map
     */
    public Map<String, Object> generationBiluFromFile(MultipartFile file1, HttpServletResponse response) {
        try {
            log.info("开始生成笔录，从立案审批表Word文件");

            // 1. 提取Word文件内容
            String documentContent = DocumentUtils.extractTextFromWord(file1);
            log.info("立案审批表文件内容提取完成，长度: {}", documentContent.length());

            // 2. 解析文本内容为JSON（这里需要AI来解析，或者假设文件内容就是JSON）
            // 为了简化，这里假设可以从文本提取关键信息或使用AI生成JSON
            // 实际应该先将文本转换为立案审批表的JSON格式

            // 简单处理：假设文件中包含JSON数据，或者使用AI重新解析
            // 这里我们直接使用文本作为输入，让InterrogationGenerationService处理
            Map<String, Object> result = interrogationGenerationService.generateInterrogationRecord(
                    documentContent, null);

            log.info("笔录生成成功");
            return result;

        } catch (Exception e) {
            log.error("生成笔录失败", e);
            throw new BusinessException(500, "生成笔录失败: " + e.getMessage());
        }
    }

}
